from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth import logout
from django.views.generic.simple import direct_to_template
from planner.models import UserProfile
from planner.models import Course
from planner.models import Department
from planner.models import Assignment
from planner.models import UserAssignment
from datetime import date
import json

def main(request):
  # Get user
  if request.user.is_authenticated():
    # Show normal screen
    profile = UserProfile.objects.get(user=request.user)
    courses = profile.courses.all()
    raw_data = json.loads(profile.raw_data)
    if 'image' in raw_data:
      image = raw_data['image']
    else:
      image = None
    posts = Assignment.objects.filter(course__in=profile.courses.all()).order_by('due')
    return render_to_response('main.html', {
      'profile': profile,
      'courses': courses,
      'posts': posts,
      'image_url': image
    })
  else:
    # Sign in or log in
    return render_to_response('signup.html', {})
    
def course_autocomplete(request):
  # Input: term
  # Output: json array
  term = request.GET['term']
  terms = term.split(' ')
  # at least 1 word
  dept = None
  if terms and Department.objects.filter(short_name__iexact=terms[0]):
    dept = Department.objects.get(short_name__iexact=terms[0])
    remaining = ''.join(terms[1:]) if len(terms) > 1 else ''
  elif len(terms) >= 2 and Department.objects.filter(short_name__iexact='%s %s' % (terms[0], terms[1])):
    dept = Department.objects.get(short_name__iexact='%s %s' % (terms[0], terms[1]))
    remaining = ''.join(terms[2:]) if len(terms) > 2 else ''
  if not dept:
    depts = Department.objects.filter(short_name__istartswith=request.GET['term'])
    results = []
    for dept in depts:
      results.append(dept.short_name)
  else:
    courses = Course.objects.filter(number__istartswith=remaining, dept=dept)
    results = []
    for course in courses[:5]:
      results.append('%s %s' % (dept.short_name, course.number))
  return HttpResponse(json.dumps(results))
  
def add_class(request):
  # REST call for adding a class
  # Input: term: Course
  # Output: result: success/fail, course: course name
  term = request.GET['term']
  terms = term.split(' ')
  if len(terms) >= 2:
    dept_name = ' '.join(terms[0:-1])
    course_num = terms[-1]
    if Course.objects.filter(dept__short_name__istartswith=dept_name, number__iexact=course_num):
      # Successful lookup
      course = Course.objects.get(dept__short_name__istartswith=dept_name, number__iexact=course_num)
      profile = UserProfile.objects.get(user=request.user)
      profile.courses.add(course)
      for assignment in Assignment.objects.filter(course=course, due__gte=date.today()):
        ua = UserAssignment(assignment=assignment, user_profile=profile)
        ua.save()
      return HttpResponse(json.dumps({'result':'success', 'course': str(course)}))
    else:
      return HttpResponse(json.dumps({'result':'fail', 'detail': '%s, %s' % (dept_name, course_num)}))
  return HttpResponse(json.dumps({'result':'fail'}))
  
def remove_class(request):
  # REST call for removing a class
  # Input: term: Course
  # Output: result: success/fail
  term = request.GET['term']
  terms = term.split(' ')
  if len(terms) >= 2:
    dept_name = ' '.join(terms[0:-1])
    course_num = terms[-1]
    if Course.objects.filter(dept__short_name__istartswith=dept_name, number__iexact=course_num):
      # Successful lookup
      course = Course.objects.get(dept__short_name__istartswith=dept_name, number__iexact=course_num)
      profile = UserProfile.objects.get(user=request.user)
      profile.courses.remove(course)
      return HttpResponse(json.dumps({'result':'success', 'course': str(course)}))
    else:
      return HttpResponse(json.dumps({'result':'fail', 'detail': '%s, %s' % (dept_name, course_num)}))
  return HttpResponse(json.dumps({'result':'fail'}))
  
def new_post(request):
  # Input: (POST) name, course, date
  # Output: result: success/fail
  name = request.GET['name']
  course = request.GET['course']
  date = request.GET['date']
  course_terms = course.split(' ')
  if len(course_terms) >= 2:
    dept_name = ' '.join(course_terms[0:-1])
    course_num = course_terms[-1]
    course = Course.objects.get(dept__short_name__istartswith=dept_name, number__iexact=course_num)
  else:
    return HttpResponse(json.dumps({'result': 'fail'}))
  if Assignment.objects.filter(name__iexact=name, course=course):
    post = Assignment.objects.get(name__iexact=name, course=course)
    post.due = date
    return HttpResponse(json.dumps({'result':'success'}))
  else:
    post = Assignment(name=name, course=course, due=date, added_by=request.user)
    post.save()
    ua = UserAssignment(user_profile=UserProfile.objects.get(user=request.user), assignment=post)
    ua.save()
    return HttpResponse(json.dumps({'result':'success'}))
  
def assignment_lookup(request, course_name, assignment):
  # Output: 
  term = course_name
  terms = term.split(' ')
  if len(terms) >= 2:
    dept_name = ' '.join(terms[0:-1])
    course_num = terms[-1]
    if Course.objects.filter(dept__short_name__istartswith=dept_name, number__iexact=course_num):
      # Successful lookup
      course = Course.objects.get(dept__short_name__istartswith=dept_name, number__iexact=course_num)
      post = Assignment.objects.get(course=course, name__iexact=assignment)
      ua = UserAssignment.objects.get_or_create(profile=UserProfile.objects.get(user=request.user), assignment=post)
      return HttpResponse(json.dumps({'result': 'success', 'done': ua.done, 'hide': ua.hide}))
      
def done(request, course_name, assignment):
  # hide an assignment, deletes it if user is the creator
  if Course.objects.filter(short_name=course_name):
    course = Course.objects.get(short_name=course_name)
    post = Assignment.objects.get(course=course, name__iexact=assignment)
    ua = UserAssignment.objects.get(user_profile=UserProfile.objects.get(user=request.user), assignment=post)
    ua.done = not ua.done
    ua.save()
    return HttpResponse(json.dumps({'result': 'success', 'done': ua.done, 'hide': ua.hide}))    

def hide(request, course_name, assignment):
  # hide an assignment, deletes it if user is the creator
  if Course.objects.filter(short_name=course_name):
    course = Course.objects.get(short_name=course_name)
    post = Assignment.objects.get(course=course, name__iexact=assignment)
    if post.added_by == request.user:
      post.delete()
      return HttpResponse(json.dumps({'result': 'success'}))    
    else:
      ua = UserAssignment.objects.get(user_profile=UserProfile.objects.get(user=request.user), assignment=post)
      ua.hide = True
      ua.save()
      return HttpResponse(json.dumps({'result': 'success', 'done': ua.done, 'hide': ua.hide}))    
  
def course(request, course_name):
  if Course.objects.filter(short_name__iexact=course_name):
    profile = UserProfile.objects.get(user=request.user)
    raw_data = json.loads(profile.raw_data)
    if 'image' in raw_data:
      image = raw_data['image']
    else:
      image = None
    profile = UserProfile.objects.get(user=request.user)
    courses = profile.courses.all()
    course = Course.objects.get(short_name__iexact=course_name)
    posts = Assignment.objects.filter(course=course, due__gte=date.today()).order_by('due')[:10]
    return render_to_response('course.html', {
      'profile': profile,
      'course': course,
      'posts': posts,
      'courses': courses,
      'image_url': image
    })
    
def logout_view(request):
  if request.user.is_authenticated():
    logout(request)
  return HttpResponseRedirect("/")
  
def assignment(request, course_name, assignment):
  term = course_name
  terms = term.split(' ')
  if len(terms) >= 2:
    dept_name = ' '.join(terms[0:-1])
    course_num = terms[-1]
    if Course.objects.filter(dept__short_name__istartswith=dept_name, number__iexact=course_num):
      # Successful lookup
      course = Course.objects.get(dept__short_name__istartswith=dept_name, number__iexact=course_num)
      post = Assignment.objects.get(course=course, name__iexact=assignment)
      return HttpResponse('Success.  Course: %s (%s).  Assignment %s' % (str(course), course.long_name, post.name))
